const qs = (element) => document.querySelector(element)
// todo 需求

axios.defaults.baseURL = 'http://124.223.14.236:3001/api'


async function init() {
    const { data: res } = await axios.get('/city/province')
    // console.log(res.data) // 省份数组

    // map join innerHTML 渲染
    const provinceStr = res.data
        .map((item) => `<option value="${item.province}">${item.name}</option>`)
        .join('')
    // console.log(provinceStr)

    qs('#province').innerHTML =
        '<option value="">请选择省份</option>' + provinceStr

    // 34 就是安徽省的编码，让安徽省展示
    qs('#province').value = 34


    const {
        data: { data: cityData },
    } = await axios.get('/city/city', {
        // ! get请求方式，需要在params 中带参数
        params: {
            provinceCode: '34',
        },
    })
    console.log(cityData)

    const cityStr = cityData
        .map((item) => `<option value="${item.city}">${item.name}</option>`)
        .join('')
    // console.log(cityStr)

    qs('#city').innerHTML = '<option value="">请选择城市</option>' + cityStr

    // 默认展示合肥市
    qs('#city').value = '01'

    const {
        data: { data: areaData },
    } = await axios.get('/city/area', {
        // ! get请求方式，需要在params 中带参数
        params: {
            provinceCode: '34',
            cityCode: '01',
        },
    })
    console.log(areaData)

    const areaStr = areaData
        .map((item) => `<option value="${item.area}">${item.name}</option>`)
        .join('')
    // console.log(areaStr)

    qs('#county').innerHTML = '<option value="">请选择区县</option>' + areaStr

    // 默认展示瑶海区
    qs('#county').value = '02'
}
init()

// 省注册change事件
qs('#province').addEventListener('change', async function () {
    console.log(this.value) // 省下拉框的值(就是省的编码)
    const {
        data: { data: cityData },
    } = await axios.get('/city/city', {
        // ! get请求方式，需要在params 中带参数
        params: {
            provinceCode: this.value,
        },
    })
    // console.log(cityData)

    const cityStr = cityData
        .map((item) => `<option value="${item.city}">${item.name}</option>`)
        .join('')
    // console.log(cityStr)

    qs('#city').innerHTML = '<option value="">请选择城市</option>' + cityStr

    // 解决bug： 需要重置区县数据
    qs('#county').innerHTML = '<option value="">请选择区县</option>'
})
qs('#city').addEventListener('change', async function () {
    console.log(this.value) // 城市的编码

    const {
        data: { data: areaData },
    } = await axios.get('/city/area', {
        // ! get请求方式，需要在params 中带参数
        params: {
            provinceCode: qs('#province').value,
            cityCode: this.value,
        },
    })
    // console.log(areaData)

    const areaStr = areaData
        .map((item) => `<option value="${item.area}">${item.name}</option>`)
        .join('')
    // console.log(areaStr)

    qs('#county').innerHTML = '<option value="">请选择区县</option>' + areaStr
})
